<template>
  <!-- 3.275 是 SearchMain.vue 裡的 TopTabs 高度 -->
  <ScrollTabView v-model="media" :tab-options="TAB_MEDIA" :height-trim-rem="3.275" @load="nextPage">
    <template #outer-tabs>
      <div class="gap-col-16">
        <div class="px-4">
          <Banner v-if="showAd" :item="ad" size="md" :event-id="64"></Banner>
          <SearchInput></SearchInput>
        </div>
        <keep-alive>
          <component :is="comp"></component>
        </keep-alive>
      </div>
    </template>
    <template v-if="fetcher" #tab-content-1>
      <MediaRow
        :items="fetcher.video.dataList"
        :loading="fetcher.video.loading"
        :no-more="fetcher.video.noMore"
        @click:item="onItemClick"
      ></MediaRow>
    </template>
    <template v-if="fetcher" #tab-content-2>
      <MediaRow
        :items="fetcher.photo.dataList"
        :loading="fetcher.photo.loading"
        :no-more="fetcher.photo.noMore"
        @click:item="onItemClick"
      ></MediaRow>
    </template>
  </ScrollTabView>
</template>
<script setup>
import { computed, provide, ref } from 'vue'
import { storeToRefs } from 'pinia'
import Home from '@/pages/search/children/Home.vue'
import Result from '@/pages/search/children/Result.vue'
import { useSearchResultStore, useSearchStore } from '@/store/search'
import Banner from '@/components/banner/Banner.vue'
import ScrollTabView from '@/components/layout/ScrollTabView.vue'
import MediaRow from '@/components/media/MediaRow.vue'
import SearchInput from '@/components/search/SearchInput.vue'
import { MEDIA_TYPE } from '@/constant'
import { TAB_MEDIA } from '@/constant/config'
import { trackEvent } from '@/gtm'
import API from '@/http'

const ad = ref(null)
const showAd = ref(true)
API.App.getAd({ data: { type: 2 } }).then((d) => {
  if (d) {
    ad.value = d
  } else {
    showAd.value = false
  }
})

const { hasSearchText } = storeToRefs(useSearchResultStore())

const comp = computed(() => (hasSearchText.value ? Result : Home))

const searchStore = useSearchStore()
const { media: currMedia, rootScrollTabViewFetcher: fetcher } = storeToRefs(searchStore)
const { toIndexedMainViewer } = searchStore
const media = computed({
  get: () => (fetcher.value ? currMedia.value : null),
  set: (v) => (currMedia.value = v),
})
function nextPage() {
  if (fetcher.value) {
    fetcher.value[media.value === MEDIA_TYPE.VIDEO ? 'video' : 'photo'].nextPage()
  }
}
function onItemClick(index) {
  toIndexedMainViewer(index)

  // Home 頁要 gtm
  if (!hasSearchText.value) {
    const item = fetcher.value[media.value === MEDIA_TYPE.VIDEO ? 'video' : 'photo'].dataList[index]
    const key = media.value === MEDIA_TYPE.VIDEO ? 33 : 34
    trackEvent({ key, value: null, meta: { aff: item.aff, id: item.id } })
  }
}

// 提供 eventId 给 MediaColumn 用
provide('adEventId', 65)
</script>
